package com;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * auth.jdbcAuthentication().dataSource(dataSource)
     * authorizeRequests()方法后，就可以添加自定义拦截路径
     * antMatchers()方法配置了请求路径
     * hasRole()和permitAll()指定了访问规则 (需要成对出现)
     * 如下：分别表示拥有“admin”权限的用户才能访问、所有用户可以访问。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user", "/menu").hasRole("admin")
                .antMatchers("/", "/**").permitAll();
    }

    @Override
    /**
     * 这个方法将指使Spring Security去找到用户列表，然后再与想要通过拦截器的用户进行比对，再进行下面的步骤。
     * */
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 自定义用户存储： 内存、数据库、LDAP......
         */
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("admin").password(passwordEncoder().encode("123456")).authorities("ADMIN")
                .and()
                .withUser("user").password(passwordEncoder().encode("123456")).authorities("ORDINARY");
    }
    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
